package cn.net.autocode.platform.providers;

import cn.hutool.core.util.StrUtil;
import cn.net.autocode.platform.exception.PlatformQueryException;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import cn.net.autocode.core.bean.ResultT;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


@RestController
@RequestMapping("autocode/updateProvider")
public class UpdateProviderCtrl extends ProviderCtrl{

    @RequestMapping("{tableId}/{fieldName}")
    @Transactional
    public ResultT execute(@PathVariable("tableId") String tableId,@PathVariable("fieldName") String fieldName,@RequestBody JSONObject data) throws PlatformQueryException {

        if(data.isEmpty()){
            return ResultT.success();
        }

        if(!data.containsKey(fieldName)){//更新操作
            return ResultT.success();
        }

        //处理ID
        if(StrUtil.isBlank(data.getString("id"))){//更新操作
            return ResultT.success();
        }

        JSONObject table = this.tableMsg(tableId);
        String tableName = table.getString("tableName");
        //更新数据内容
        String columnName = this.getColumnName(table.getString("id"),fieldName);
        if(StrUtil.isBlank(columnName)){
            return ResultT.success();
        }

        String sql = "update "+tableName+" set "+columnName+"=? where id=?";

        //
        Object value = data.get(fieldName);
        String strValue;
        if (value==null){
            strValue = null;
        }else if(value instanceof JSONArray){
           strValue = ((JSONArray) value).toJSONString();
        }else if(value instanceof JSONObject){
            strValue = ((JSONObject) value).toJSONString();
        }else if(value instanceof List){
            strValue = JSONArray.toJSONString(value);
        }else if(value instanceof String)
        {
            if(((String) value).isBlank()){
                strValue = null;
            }else{
                strValue = value.toString();
            }
        }else{
            strValue = value.toString();
        }

        //处理ID
        dao.executeUpdate(sql,strValue,data.getString("id"));
        return ResultT.success();
    }


}
